// ie11 not support browser-md5-file
// import MD5 from 'browser-md5-file';

const helper = {

	parseXml: (text, tagName) => {
		var parser = new window.DOMParser();
		var xml = parser.parseFromString(text.replace(/&lt;/g, '<').replace(/&gt;/g, '>'), 'text/xml');
		var value = {};

		tagName = Array.isArray(tagName) ? tagName : [tagName];

		tagName.map(e => {
			value[e] = xml.getElementsByTagName(e)[0].childNodes[0].nodeValue;
		});

		return {
			xml,
			value
		};
	},

	humanSize: (size) => {
		var value = (size / 1024).toFixed(1);

		if (size > (1024 << 10)) {
			value = (value / 1024).toFixed(1);
			return `${value} M`;
		} else {
			return `${value} KB`;
		}
	},

	getFiletypeIcon: (extension) => {
		var filename = 'unknow';

		extension = (extension || '').toLowerCase().replace(/^\./, '');

		switch (true) {
			case ['mp3', 'flac', 'aac', 'm4a', 'wma'].includes(extension):
				filename = 'audio';
				break;

			case ['mp4', 'mkv', 'avi', 'flv'].includes(extension):
				filename = 'audio';
				break;

			case ['zip', 'rar', 'tar', 'tar.gz'].includes(extension):
				filename = 'archive';
				break;

			case ['doc', 'docx'].includes(extension):
				filename = 'word';
				break;

			case ['xls', 'xlsx'].includes(extension):
				filename = 'excel';
				break;

			case ['ai', 'apk', 'exe', 'ipa', 'pdf', 'ppt', 'psd'].includes(extension):
				filename = extension;
				break;
			default:
				break;
		}

		return `${filename}.png`;
	},

	getPallet: (image) => {
		return new Promise((resolve, reject) => {
			new window.AlbumColors(image).getColors((colors, err) => {
				if (err) {
					resolve([
						[0, 0, 0],
						[0, 0, 0],
						[0, 0, 0],
					]);
				} else {
					resolve(colors);
				}
			});
		});
	},

	decodeHTML: (text = '') => {
		return text.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
	},

	isImage: (ext) => {
		return ['bmp', 'gif', 'jpeg', 'jpg', 'png'].includes(ext);
	},

	// 3 types supported: pic, video, doc
	getMediaType: (ext = '') => {
		ext = ext.toLowerCase();

		switch (true) {
			case helper.isImage(ext):
				return 'pic';

			case ['mp4'].includes(ext):
				return 'video';

			default:
				return 'doc';
		}
	},

	getDataURL: (src) => {
		var image = new window.Image();

		return new Promise((resolve, reject) => {
			image.src = src;
			image.onload = () => {
				var canvas = document.createElement('canvas');
				var context = canvas.getContext('2d');

				canvas.width = image.width;
				canvas.height = image.height;

				context.drawImage(image, 0, 0, image.width, image.height);
				resolve(canvas.toDataURL('image/png'));
			};

			image.onerror = () => {
				resolve('');
			};
		});
	},

	// md5: (file) => {
	//     return new Promise((resolve, reject) => {
	//         new MD5().md5(file, (err, md5) => {
	//             resolve(err ? false : md5);
	//         });
	//     });
	// },

	weekFormat: (num) => {
		let str
		switch (num) {
			case 1:
				str = '星期一'
				break
			case 2:
				str = '星期二'
				break
			case 3:
				str = '星期三'
				break
			case 4:
				str = '星期四'
				break
			case 5:
				str = '星期五'
				break
			case 6:
				str = '星期六'
				break
			default:
				str = '星期天'
		}
		return str
	},
	// 获取某一天
	getDay(num, str) {
		let today = new Date();
		let nowTime = today.getTime();
		let ms = 24 * 3600 * 1000 * num;
		today.setTime(parseInt(nowTime + ms));
		let oYear = today.getFullYear();
		let oMoth = (today.getMonth() + 1).toString();
		if (oMoth.length <= 1) oMoth = "0" + oMoth;
		let oDay = today.getDate().toString();
		if (oDay.length <= 1) oDay = "0" + oDay;
		return oYear + str + oMoth + str + oDay;
	},
	//获取某一天的前一天
	getYesterday(date) {
		var date = date.split('-'),
			today = new Date().setFullYear(+date[0], +date[1] - 1, +date[2]),
			yesterday = new Date(today - 24 * 60 * 60 * 1000);
		var y = yesterday.getFullYear();
		var m = yesterday.getMonth() + 1;
		var d = yesterday.getDate();
		if (m < 10) {
			m = '0' + m;
		}
		if (d < 10) {
			d = '0' + d;
		}

		return y + '-' + m + '-' + d;
	},
	// 时间描述
	dateDesc(time) {
		let str = '';
		if (time < 12) {
			str = '上午' + time + '点'
		} else if (time == 12) {
			str = '中午' + time + '点'
		} else {
			str = '下午' + (time - 12) + '点'
		}
		return str;
	},
	getNowDay() {
		var date = new Date(); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
		var Y = date.getFullYear() + '-';
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
		var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
		var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
		var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
		var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
		return Y + M + D + h + m + s;
	},
	rad(d) {
		return d * Math.PI / 180.0;
	},
	getDistances(lat1, lng1, lat2, lng2, type) {
		var radLat1 = this.rad(lat1);
		var radLat2 = this.rad(lat2);
		var a = radLat1 - radLat2;
		var b = this.rad(lng1) - this.rad(lng2);
		var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
			Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
		s = s * 6378.137; // EARTH_RADIUS;
		// 输出为公里
		s = Math.round(s * 10000) / 10000;

		var distance = s;
		var distance_str = "";

		if (parseInt(distance) >= 1) {
			// distance_str = distance.toFixed(1) + "km";
			distance_str = parseFloat(distance.toFixed(2)) + "千米";
		} else {
			// distance_str = distance * 1000 + "m";
			distance_str = (distance * 1000).toFixed(0) + "米";
		}
		//小小修改，这里返回对象
		let objData = {
			distance: distance,
			distance_str: distance_str
		}
		return type ? distance : distance_str
	},
	setTime(date) { //获取多少秒/分钟/天/月/年前
		if (!date) {
			return ""
		}
		date = date.replace(/-/g, '/');
		var dateTime = new Date(date);
		var timespan = Date.parse(dateTime) / 1000;
		var year = dateTime.getFullYear();
		var month = dateTime.getMonth() + 1;
		var day = dateTime.getDate();
		var hour = dateTime.getHours();
		var minute = dateTime.getMinutes();

		//当前时间
		var now = Date.parse(new Date()); //typescript转换写法
		var milliseconds = 0;
		var timeSpanStr;
		//计算时间差
		milliseconds = (now / 1000) - timespan;

		//一分钟以内
		if (milliseconds <= 60) {
			timeSpanStr = '刚刚';
		}
		//大于一分钟小于一小时
		else if (60 < milliseconds && milliseconds <= 60 * 60) {
			timeSpanStr = Math.ceil((milliseconds / (60))) + '分钟前';
		}
		//大于一小时小于等于一天
		else if (60 * 60 < milliseconds && milliseconds <= 60 * 60 * 24) {
			timeSpanStr = Math.ceil(milliseconds / (60 * 60)) + '小时前';
		}
		//大于一天小于等于30天
		else if (60 * 60 * 24 < milliseconds && milliseconds <= 60 * 60 * 24 * 30) {
			timeSpanStr = Math.ceil(milliseconds / (60 * 60 * 24)) - 1 + '天前';
		}
		//大于一个月小于一年
		else if (60 * 60 * 24 * 30 < milliseconds && milliseconds <= 60 * 60 * 24 * 30 * 12) {
			timeSpanStr = Math.ceil(milliseconds / (60 * 60 * 24 * 30)) + '个月前';
		}
		//超过一年显示
		else {
			timeSpanStr = year + '年' + month + '月' + day + '日 ' + hour + ':' + minute;
		}
		return timeSpanStr;
	},
	getDaysBetweenDates(date1, date2) { // 获取两日期间差值天数
		date1 = new Date(date1)
		date2 = new Date(date2)
		let oneDay = 24 * 60 * 60 * 1000;
		let diffDays = Math.round(Math.abs((date1 - date2) / oneDay));
		return diffDays;
	},
	paymentTypeStr(orderChannel, type) {
		let list = [];
		if (orderChannel === 0) { //线下
			list = ['微信收款码', '支付宝收款码', '银联云闪付收款码', '钱包', '现金', '其他', '微信小程序支付'];
		} else { //线上
			list = ['微信线上支付', '支付宝线上支付', '银联云闪付收款码', '钱包', '现金', '其他', '微信小程序支付'];
		}
		return list[type];
	},
};


export default helper;